package com.udata.client.view.impl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import com.udata.client.place.DashboardPlace;
import com.udata.client.service.UserService;
import com.udata.client.service.UserServiceAsync;
import com.udata.client.view.UserView;
import com.udata.shared.CookiesConfig;
import com.udata.shared.exception.OperationException;
import com.udata.shared.model.UserB;

public class UserRegisterViewImpl extends Composite implements UserView {
  private static UserRegisterViewImplUiBinder uiBinder = GWT
                                                           .create(UserRegisterViewImplUiBinder.class);

  interface UserRegisterViewImplUiBinder extends UiBinder<Widget, UserRegisterViewImpl> {
  }

  UserServiceAsync instanceService = (UserServiceAsync) GWT.create(UserService.class);

  interface Style extends CssResource {

  }

  @UiField
  Style             style;

  @UiField
  TextBox           emailRegTextBox;
  @UiField
  TextBox           passwordRegTextBox;
  @UiField
  TextBox           nameRegTextBox;

  @UiField
  HTMLPanel         mainPanel;

  @UiField
  HTMLPanel         registerPanel;

  @UiField
  Label             registerStatus;

  @UiField
  Button            saveButton;

  private Presenter presenter;
  
  public boolean statusOk=false;

  public UserRegisterViewImpl() {
    initWidget(uiBinder.createAndBindUi(this));
    registerStatus.setText("");
  }

  @UiHandler("saveButton")
  public void clickSaveButton(ClickEvent clickEvent) {
    UserB userB = new UserB();
    String email = emailRegTextBox.getText();
    if (this.emailFormatCheck(email)) {
      userB.setEmail(email);
      String name = nameRegTextBox.getText();
      if (this.nameFormatCheck(name)) {
        userB.setName(name);
        String password = passwordRegTextBox.getText();
        if (this.passwordFormatCheck(password)) {

          userB.setPassword(password);

          instanceService.registerUser(userB, new AsyncCallback<UserB>() {

            @Override
            public void onFailure(Throwable caught) {
              GWT.log(caught.getLocalizedMessage());
              registerStatus.setText("The username or password you entered is incorrect.");
            }

            @Override
            public void onSuccess(UserB result) {
              if (result == null) {
                registerStatus
                    .setText("The user name is already exist, please choose another one.");
              } else {
                Cookies.setCookie(CookiesConfig.USERNAME, result.getName());
                Cookies.setCookie(CookiesConfig.EMAIL, result.getEmail());
                presenter.goTo(new DashboardPlace("dashboard"));
              }
            }
          });
        } else {
          registerStatus.setText("Please input right password");

        }
      } else {
        registerStatus.setText("Please input right name");

      }
    } else {
      registerStatus.setText("Please input right email adress");
    }

  }

  @UiHandler("emailRegTextBox")
  public void blurEmailRegTextBox(BlurEvent blurEvent) {
    String email = emailRegTextBox.getText();

    instanceService.getUser(email, new AsyncCallback<UserB>() {

      @Override
      public void onFailure(Throwable caught) {
        registerStatus.setText("The user name is already exist, please choose another one.");
      }

      @Override
      public void onSuccess(UserB result) {
        if (result == null) {
          registerStatus.setText("The user name is already exist, please choose another one.");
        }
      }
    });
  }

  private Boolean emailFormatCheck(String email) {
    if (email == null) {
      return false;
    }
    RegExp regexExp = RegExp.compile(".+@.+\\.[a-z]+");
    MatchResult m = regexExp.exec(email);
    if (m.getGroupCount() == 0) {
      return false;
    } else {
      return true;
    }
  }

  private Boolean nameFormatCheck(String name) {
    if (name == null) {
      return false;
    }

    RegExp pattern = RegExp.compile("[\\w]{1,20}");

    MatchResult m = pattern.exec(name);
    if (m.getGroupCount() == 0) {
      return false;
    } else {
      return true;
    }

  }

  private Boolean passwordFormatCheck(String password) {
    if (password == null) {
      return false;
    }

    RegExp pattern = RegExp.compile("[^\\s]{6,20}");

    MatchResult m = pattern.exec(password);
    if (m.getGroupCount() == 0) {
      return false;
    } else {
      return true;
    }

  }

  @Override
  public void setPresenter(Presenter presenter) {
    this.presenter = presenter;
  }

}